package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.omg.CORBA.TIMEOUT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    private Map<String,Object> cache =new HashMap<>();

    /*@Autowired
    CategoryDao categoryDao;*/

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {

        //1.查出所有的分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //2.组装成父子的属性结构
           /*一级分类*/
        List<CategoryEntity> level1Menus=entities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid()==0
                ).map((menu)->{
                    menu.setChildren(getChildrens(menu,entities));
                    return menu;
                }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
                }).collect(Collectors.toList());

        return level1Menus;
    }
   /*菜单删除的方法*/
    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 1.检查当前删除的菜单，是否被别的地方引用
        baseMapper.deleteBatchIds(asList);
    }

    /*找到catelogId的完整路径
    * 【父\子\孙】
    * */
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths=new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
        return  parentPath.toArray(new Long[parentPath.size()]);
    }
/*级联更新所有关联的数据*/
    /*同时进行多种缓存操作*/
/*    @Caching(
            evict = {
                    @CacheEvict(value = "category",key="'getLevel1Categorys'"), *//*缓存失效*//*
                    @CacheEvict(value = "category",key = "'getCatalogJson'")
            }
    )*/
    /*也可以使用这个注解同时删除分区中的所有的内容*/
   //@CachePut 双写模式
   @CacheEvict(value = "category",allEntries = true)  //失效模式
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());

    }
    //每一个需要缓存的数据我们呢都来指定要放到那个名字的缓存（按照业务类型进行区分）
    @Cacheable(value={"category"},key = "#root.method.name",sync = true) //代表当前的方法的结果需要缓存，如有缓存，方法不用调用，如果缓存中没有，会调用方法，最后将结果放入缓存中
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }
    @Cacheable(value = "category",key="#root.methodName")
    @Override
    public Map<String,List<Catelog2Vo>> getCatalogJson(){
        System.out.println("查询数据库");

        /*1.将数据的多次查询变为一次*/
        List<CategoryEntity> selectList = baseMapper.selectList(null);


        //查出所有的一级分类
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);
        //2.封装数据
        Map<String, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                //封装上边的结果

                catelog2Vos = categoryEntities.stream().map(l2 -> {
//                    new Catelog2Vo(v.getCatId().toString(),"","");
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());

                    //1找当前二级分类的三级分类
                    List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());

                    if (level3Catelog != null) {
                        List<Catelog2Vo.Catelog3Vo> collect = level3Catelog.stream().map(l3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect);
                    }


                    return catelog2Vo;
                }).collect(Collectors.toList());
            }


            return catelog2Vos;

        }));


        return parent_cid;
    }

    //@Override
    /*加入缓存来缓解服务器压力的方法*/
    public Map<String, List<Catelog2Vo>> getCatalogJson2() {
//        加入缓存逻辑，缓存中所有的对象都是json字符串
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if(StringUtils.isEmpty(catalogJSON)){
            System.out.println("缓存不命中,查询数据库");
//            2.缓存中没有
            Map<String, List<Catelog2Vo>> catalogJsonFormDb = getCatalogJsonFormDbWithRedisLock();

            return catalogJsonFormDb;

        }
        System.out.println("缓存命中。。直接返回");
        Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {

        });


        return result;
    }

   //从数据库查询数据并封装三级菜单数据
    public Map<String, List<Catelog2Vo>> getCatalogJsonFormDbWithRedisLock() {

//        1.站分布式锁。去占坑


        return getDataFromDb();


    }

    private Map<String, List<Catelog2Vo>> getDataFromDb() {
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");

        if (!StringUtils.isEmpty(catalogJSON)) {

            //缓存不为空直接返回
            Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {

            });
            return result;
        }
        System.out.println("查询数据库");

        /*1.将数据的多次查询变为一次*/
        List<CategoryEntity> selectList = baseMapper.selectList(null);


        //查出所有的一级分类
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);
        //2.封装数据
        Map<String, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                //封装上边的结果

                catelog2Vos = categoryEntities.stream().map(l2 -> {
//                    new Catelog2Vo(v.getCatId().toString(),"","");
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());

                    //1找当前二级分类的三级分类
                    List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());

                    if (level3Catelog != null) {
                        List<Catelog2Vo.Catelog3Vo> collect = level3Catelog.stream().map(l3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect);
                    }


                    return catelog2Vo;
                }).collect(Collectors.toList());
            }


            return catelog2Vos;

        }));
        //            3.查到的数据在放入缓存，将对象转为json放在缓存中
        String s = JSON.toJSONString(parent_cid);
        redisTemplate.opsForValue().set("catalogJSON", s, 1, TimeUnit.DAYS);

        return parent_cid;
    }




    public Map<String, List<Catelog2Vo>> getCatalogJsonFormDbWithLocalLock() {
//         1.占用分布式锁，去redis占坑
        String uuid = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 300,TimeUnit.SECONDS);
        if(lock){
            //枷锁成功   执行业务
//设置过期时间  必须是和枷锁是同步的否则出现断电等特殊情况导致代码执行一半，导致啦死锁
            //redisTemplate.expire("lock",30, TimeUnit.SECONDS);
            Map<String, List<Catelog2Vo>> dataFromDb ;
            try{
                dataFromDb = getDataFromDb();
            }finally {
                //            获取值对比+对比成功删除=原子操作 lua脚本解锁
                String script="if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                Long lock1 = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), uuid);
            }





          /*  String lockValue = redisTemplate.opsForValue().get("lock");

            if(lockValue.equals(uuid)){
                redisTemplate.delete("lock");
            }*/

            return dataFromDb;
        }else{
            //枷锁失败，重试
            getCatalogJsonFormDbWithRedisLock(); //自旋的方式
        }
        return getDataFromDb();


        }






    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList,Long parent_cid) {
        List<CategoryEntity> collect = selectList.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
        return collect;
        // return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
    }


    private List<Long> findParentPath(Long catelogId,List<Long> paths){
        //1.收集当前的节点的id
        paths.add(catelogId);
        CategoryEntity byId=this.getById(catelogId);
        if(byId.getParentCid()!=0){
            findParentPath(byId.getParentCid(),paths);
        }
        return paths;
    }



    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){

        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {
            //1.找到子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }

}
